package com.lethelh.jdbc.sample;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.lethelh.jdbc.utils.DBUtils;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class DruidSample {
    public static void main(String[] args) {
        // 1.加载属性文件
        Properties properties = new Properties();
        String propertyFile = DruidSample.class.getResource("/druid-config.properties").getPath();
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        String sql = "select * from goods;";
        try {
            propertyFile = new URLDecoder().decode(propertyFile, "UTF-8");
            properties.load(new FileInputStream(propertyFile));
            // 2.获取DataSource数据源对象
            DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
            // 3.创建数据库连接
            conn =  dataSource.getConnection();
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();

            while (rs.next()){
                int id = rs.getInt(1);
                String name =  rs.getString(2);
                double price = rs.getFloat(3);
                String desc = rs.getString(4);
                System.out.println("id:"+id+"name:"+name+"price:"+price+"desc:"+desc);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                DBUtils.closeConnection(rs, pstmt, conn);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
